package com.yootk.main;

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.util.Scanner;

/**
 * ResourceLoader，通过工厂实例化
 * 只需要注入字符串就可以自动转为Resource接口实例
 */
public class Demo05_ResourceLoader {
    public static void main(String[] args) throws Exception {
//        test1();
//        test2();
        test3();
    }

    /**
     * 实现文件数据的加载
     */
    public static void test1() throws Exception {
        ResourceLoader loader = new DefaultResourceLoader();
        Resource resource = loader.getResource("file:F:/muyan/message.txt");
        Scanner scanner = new Scanner(resource.getInputStream());   // 获取输入流
        scanner.useDelimiter("\n");     // 设置换行标记
        while (scanner.hasNext()) {
            String result = scanner.next();
            System.err.println(result);
        }
        scanner.close();
    }

    /**
     * 通过CLASSPATH加载资源
     */
    public static void test2() throws Exception {
        ResourceLoader loader = new DefaultResourceLoader();
        // ResourceUtils.CLASSPATH_URL_PREFIX + "message.txt";
        Resource resource = loader.getResource("classpath:message.txt");
        Scanner scanner = new Scanner(resource.getInputStream());   // 获取输入流
        scanner.useDelimiter("\n");     // 设置换行标记
        while (scanner.hasNext()) {
            String result = scanner.next();
            System.err.println(result);
        }
        scanner.close();
    }

    /**
     * 通过网络加载
     */
    public static void test3() throws Exception {
        ResourceLoader loader = new DefaultResourceLoader();
        Resource resource = loader.getResource("https://www.yootk.com/");
        Scanner scanner = new Scanner(resource.getInputStream());   // 获取输入流
        scanner.useDelimiter("\n");     // 设置换行标记
        while (scanner.hasNext()) {
            String result = scanner.next();
            System.err.println(result);
        }
        scanner.close();
    }
}
